<pre class=metadata>
Title: Long Tasks API
Group: webperf
Status: ED
Shortname: longtasks
Level: 1
URL: https://w3c.github.io/longtasks/
Editor: Shubhie Panicker, Google https://google.com, panicker@chromium.org
Editor: Ilya Grigorik, Google https://google.com, igrigorik@chromium.org
Editor: Domenic Denicola, Google https://google.com, domenic@chromium.org
Repository: w3c/longtasks
Test Suite: http://w3c-test.org/longtask-timing/
Abstract: This document defines an API that web page authors can use to detect presence of "long tasks" that monopolize the UI thread for extended periods of time and block other critical tasks from being executed - e.g. reacting to user input.
Status Text: If you wish to make comments regarding this document, please send them to  <a href="mailto:public-web-perf@w3.org?subject=%5BLongTasks%5D">public-web-perf@w3.org</a> (<a href="mailto:public-web-perf-request@w3.org?subject=subscribe">subscribe</a>, <a href="https://lists.w3.org/Archives/Public/public-web-perf/">archives</a>) with <code nohighlight>[LongTasks]</code> at the start of your email's subject.
Default Highlight: js
</pre>

<style>
dl {
    margin-left: 2em;
}
</style>

<pre class=anchors>
urlPrefix: https://w3c.github.io/performance-timeline/; spec: PERFORMANCE-TIMELINE-2;
    type: interface; url: #the-performanceentry-interface; text: PerformanceEntry;
    type: attribute; for: PerformanceEntry;
        text: name; url: #dom-performanceentry-name
        text: entryType; url: #dom-performanceentry-entrytype
        text: startTime; url: #dom-performanceentry-starttime
        text: duration; url: #dom-performanceentry-duration
    type: dfn; url: #dfn-queue-a-performanceentry; text: Queue the PerformanceEntry
    type: dfn; url: #dfn-register-a-performance-entry-type; text: register a performance entry type
    type: attribute; for: PerformanceObserver;
        text: supportedEntryTypes; url: #supportedentrytypes-attribute;
urlPrefix: https://w3c.github.io/hr-time/; spec: HR-TIME-2;
    type: typedef; url: #idl-def-domhighrestimestamp; text: DOMHighResTimeStamp;
    type: interface; url: #dfn-performance; text: Performance;
    type: attribute; for: Performance;
        text: now(); url: #dom-performance-now
    type: dfn; text: current high resolution time; url: #dfn-current-high-resolution-time;
urlPrefix: https://html.spec.whatwg.org/multipage/; spec: HTML;
    type: dfn; url: #definitions-3; text: event loop definitions;
    type: dfn; url: #calling-scripts; text: calling scripts;
    type: dfn; url: #list-of-the-descendant-browsing-contexts; text: list of the descendant browsing contexts;
    type: dfn; url: #ancestor-browsing-context; text: ancestor;
    type: dfn; url: #unit-of-related-browsing-contexts; text: unit of related browsing contexts
    type: dfn; url: #script-evaluation-environment-settings-object-set; text: script evaluation environment settings object set
    type: dfn; url: #integration-with-the-javascript-agent-cluster-formalism; text: agent cluster
urlPrefix: https://tc39.github.io/ecma262/; spec: ECMASCRIPT;
    type: dfn; url: #sec-code-realms; text: JavaScript Realms;
urlPrefix: https://dom.spec.whatwg.org/; spec: DOM;
    type: attribute; for: Element;
        text: id; url: #dom-element-id;
</pre>

<pre class=link-defaults>
spec:html; type:dfn; for:/; text:browsing context
</pre>

Introduction {#intro}
=====================

As the page is loading and while the user is interacting with the page afterwards, both the application and browser queue various events that are then executed by the browser -- e.g. user agent schedules input events based on user’s activity, the application schedules callbacks for requestAnimationFrame and other callbacks, etc. Once in the queue, the browser dequeues these events one-by-one and executes them.

However, some tasks can take a long time (multiple frames) and if/when that happens, the UI thread may become blocked and block all other tasks as well. To the user, this is commonly visible as a "locked up" page where the browser is unable to respond to user input; this is a major source of bad user experience on the web today:

: Delayed "time to Interactive":
:: while the page is loading, or even completely visually rendered, long tasks often tie up the main thread and prevent the user from interacting with the page. Poorly designed third-party content is frequently the culprit.

: High/variable input latency:
:: critical user-interaction events (e.g. tap, click, scroll, wheel, etc.) are queued behind long tasks which yields janky and unpredictable user experience.

: High/variable event handling latency:
:: like input, processing event callbacks (e.g. onload events, etc.) delay application updates.

: Janky animations and scrolling:
:: some animation and scrolling interactions require coordination between compositor and main threads; if a long task is blocking the main thread it can affect responsiveness of animations and scrolling.

Some applications (and <a href="https://en.wikipedia.org/wiki/Real_user_monitoring">RUM</a> vendors) are already attempting to identify and track cases where "long tasks" happen. For example, one known pattern is to install a ~short periodic timer and inspect the elapsed time between the successive expirations: if the elapsed time is greater than the timer period, then there is high likelihood that one or more long tasks have delayed execution of the event loop. This approach mostly works but has several bad performance implications: by polling to detect long tasks, the application prevents quiescence and long idle blocks (see requestIdleCallback); it’s bad for battery life; there is no way to know what is causing the delay (e.g. first party or third party code).

The <a href="https://developers.google.com/web/fundamentals/performance/rail">RAIL</a> performance model suggests that applications should respond to user input in less than 100ms (for touch move and scrolling, the threshold is 16ms). The goal of this API is to surface notifications about tasks that may prevent the application from hitting these targets. This API surfaces tasks that take 50ms or more. A website without these tasks should respond to user input in under 100ms: it will take less than 50ms to finish the task that is being executed when the user input is received and less than 50ms to execute the task to react to such user input.

Usage Example {#example}
------------------------

<pre class="example highlight">
    const observer = new PerformanceObserver(function(list) {
        for (const entry of list.getEntries()) {
            // Process long task notifications:
            // report back for analytics and monitoring
            // ...
        }
    });
    // Register observer for previous and future long task notifications.
    observer.observe({type: "longtask", buffered: true});
    // Long script execution after this will result in queueing
    // and receiving "longtask" entries in the observer.
</pre>

Terminology {#sec-terminology}
==============================

<dfn export>Long task</dfn> refers to any of the following occurrences whose duration exceeds 50ms:

* An event loop <a>task</a> plus the <a>perform a microtask checkpoint</a> that follows immediately afterwards. This captures the duration of an event loop <a>task</a>, including its associated <a>microtasks</a>.

* An <a>update the rendering</a> step within the <a>event loop processing model</a>.

* A pause between the last step and the next first step of the <a>event loop processing model</a>. This captures any work that the user agent performs in its UI thread outside of the <a>event loop</a>.

<dfn>Culprit browsing context container</dfn> refers to the <a>browsing context container</a> (<{iframe}>, <{object}>, etc.) that is being implicated, on the whole, for a <a>long task</a>.

<dfn>Attribution</dfn> refers to identifying the type of work (such as script, layout etc.) that contributed significantly to the long task, as well as identifying which <a>culprit browsing context container</a> is responsible for that work.

Long Task Timing {#sec-longtask-timing}
=======================================

Long Task timing involves the following new interfaces:

{{PerformanceLongTaskTiming}} interface {#sec-PerformanceLongTaskTiming}
------------------------------------------------------------------------

<pre class="idl">
    [Exposed=Window]
    interface PerformanceLongTaskTiming : PerformanceEntry {
        readonly attribute FrozenArray&lt;TaskAttributionTiming> attribution;
        [Default] object toJSON();
    };
</pre>

The values of the attributes of a {{PerformanceLongTaskTiming}} are set in the processing model in [[#report-long-tasks]]. The following provides an informative summary of how they will be set.

The {{PerformanceEntry/name}} attribute's getter will return one of the following strings:

: "<code><dfn>unknown</dfn></code>"
:: The long task originated from an <a>update the rendering</a> step within the <a>event loop processing model</a> or work the user agent performed outside of the <a>event loop</a>.
: "<code><dfn>self</dfn></code>"
:: The long task originated from an event loop <a>task</a> within this <a>browsing context</a>.
: "<code><dfn>same-origin-ancestor</dfn></code>"
:: The long task originated from an event loop <a>task</a> within a <a lt="same origin">same-origin</a> <a>ancestor browsing context</a>.
: "<code><dfn>same-origin-descendant</dfn></code>"
:: The long task originated from an event loop <a>task</a> within a <a lt="same origin">same-origin</a> <a lt="list of the descendant browsing contexts">descendant browsing context</a>.
: "<code><dfn>same-origin</dfn></code>"
:: The long task originated from an event loop <a>task</a> within a <a lt="same origin">same-origin</a> <a>browsing context</a> that is not an ancestor or descendant.
: "<code><dfn>cross-origin-ancestor</dfn></code>"
:: The long task originated from an event loop <a>task</a> within a cross-origin <a>ancestor browsing context</a>.
: "<code><dfn>cross-origin-descendant</dfn></code>"
:: The long task originated from an event loop <a>task</a> within a cross-origin <a lt="list of the descendant browsing contexts">descendant browsing context</a>.
: "<code><dfn>cross-origin-unreachable</dfn></code>"
:: The long task originated from an event loop <a>task</a> within a cross-origin <a>browsing context</a> that is not an ancestor or descendant.
: "<code><dfn>multiple-contexts</dfn></code>"
:: The long task originated from an event loop <a>task</a> involving multiple <a>browsing contexts</a>.

The {{PerformanceEntry/entryType}} attribute's getter will return <code>"longtask"</code>.

The {{PerformanceEntry/startTime}} attribute's getter will return a {{DOMHighResTimeStamp}} of when the task started.

The {{PerformanceEntry/duration}} attribute's getter will return a {{DOMHighResTimeStamp}} equal to the elapsed time between the start and end of task.

The <dfn attribute for=PerformanceLongTaskTiming>attribution</dfn> attribute's getter will return a frozen array of {{TaskAttributionTiming}} entries.

{{TaskAttributionTiming}} interface {#sec-TaskAttributionTiming}
----------------------------------------------------------------

<pre class="def idl">
    [Exposed=Window]
    interface TaskAttributionTiming : PerformanceEntry {
        readonly attribute DOMString containerType;
        readonly attribute DOMString containerSrc;
        readonly attribute DOMString containerId;
        readonly attribute DOMString containerName;
        [Default] object toJSON();
    };
</pre>

The values of the attributes of a {{TaskAttributionTiming}} are set in the processing model in [[#report-long-tasks]]. The following provides an informative summary of how they will be set.

The {{PerformanceEntry/name}} attribute's getter will always return "<code>unknown</code>".

The {{PerformanceEntry/entryType}} attribute's getter will always return "<code>taskattribution</code>".

The {{PerformanceEntry/startTime}} attribute's getter will always return 0.

The {{PerformanceEntry/duration}} attribute's getter will always return 0.

The <dfn attribute for=TaskAttributionTiming>containerType</dfn> attribute's getter will return the type of the <a>culprit browsing context container</a>, such as "<code>iframe</code>", "<code>embed</code>", or "<code>object</code>". If no single <a>culprit browsing context container</a> is found, it will return "<code>window</code>".

The <dfn attribute for=TaskAttributionTiming>containerName</dfn> attribute's getter will return the value of the <a lt="culprit browsing context container">container</a>'s <code>name</code> content attribute. If no single <a>culprit browsing context container</a> is found, it will return the empty string.

The <dfn attribute for=TaskAttributionTiming>containerId</dfn> attribute's getter will return the value of the <a lt="culprit browsing context container">container</a>'s <code>id</code> content attribute. If no single <a>culprit browsing context container</a> is found, it will return the empty string.

The <dfn attribute for=TaskAttributionTiming>containerSrc</dfn> attribute's getter will return the value of the <a lt="culprit browsing context container">container</a>'s <code>src</code> content attribute. If no single <a>culprit browsing context container</a> is found, it will return the empty string.

Pointing to the culprit {#sec-PointingToCulprit}
------------------------------------------------

<div class=non-normative>

<em>This section is non-normative.</em>

A <a>long task</a> can involve different types of work (such as script, layout, style etc), and it could be executed within different <a>browsing contexts</a>, or it could be global in nature such as a long garbage collection that spans the entire <a>agent cluster</a> or <a>unit of related browsing contexts</a>.

Thus <a>attribution</a> has a couple of facets:

* Pointing to the origin of the long task and/or the overall location of the <a lt="culprit browsing context container">culprit browsing context</a>: this is referred to as <dfn>minimal culprit attribution</dfn> and is captured in the {{PerformanceEntry/name}} field.

* Pointing to the type of work involved in the <a>long task</a>, and its associated <a>culprit browsing context container</a>: this is captured in {{TaskAttributionTiming}} objects in the {{PerformanceLongTaskTiming/attribution}} field of {{PerformanceLongTaskTiming}}.

Therefore, {{PerformanceEntry/name}} and {{PerformanceLongTaskTiming/attribution}} fields on {{PerformanceLongTaskTiming}} together paint the picture for where the blame rests for a long task.
When delivering this information the Web's same-origin policy must be adhered to.

These fields are not independent. The following gives an overview of how they are related:

<table>
    <thead>
        <tr>
            <th>{{PerformanceEntry/name}}</th>
            <th><a>Culprit browsing context container</a> implicated by {{PerformanceLongTaskTiming/attribution}}</th>
    <tbody>
        <tr>
            <td>"<code><a>self</a></code>"
            <td>empty
        <tr>
            <td>"<code><a>same-origin-ancestor</a></code>"
            <td>same-origin culprit
        <tr>
            <td>"<code><a>same-origin-descendant</a></code>"
            <td>same-origin culprit
        <tr>
            <td>"<code><a>same-origin</a></code>"
            <td>same-origin culprit
        <tr>
            <td>"<code><a>cross-origin-ancestor</a></code>"
            <td>empty
        <tr>
            <td>"<code><a>cross-origin-descendant</a></code>"
            <td>empty
        <tr>
            <td>"<code><a>cross-origin-unreachable</a></code>"
            <td>empty
        <tr>
            <td>"<code><a>multiple-contexts</a></code>"
            <td>empty
        <tr>
            <td>"<code><a>unknown</a></code>"
            <td>empty
</table>

</div>

Processing model {#sec-processing-model}
========================================

Note: A user agent implementing the Long Tasks API would need to include <code>"longtask"</code> in {{PerformanceObserver/supportedEntryTypes}} for {{Window}} contexts.
This allows developers to detect support for long tasks.

Report long tasks {#report-long-tasks}
--------------------------------------------------------

<div algorithm="Report long tasks">
    Given |start time|, |end time|, |top-level browsing contexts|, and optionally |task|, perform the following algorithm:

    1. If |end time| minus |start time| is less than the long tasks threshold of 50 ms, abort these steps.

    1. Let |destinationRealms| be an empty set.

    1. Determine the set of <a>JavaScript Realms</a> to which reports will be delivered:

        For each <a>top-level browsing context</a> |topmostBC| in |top-level browsing contexts|:

        1. Add |topmostBC|'s Window's <a>relevant Realm</a> to |destinationRealms|.
        1. Let |descendantBCs| be |topmostBC|'s <a>active document</a>'s <a>list of the descendant browsing contexts</a>.
        1. For each |descendantBC| in |descendantBCs|, add |descendantBC|'s Window's <a>relevant Realm</a> to |destinationRealms|.

    1. For each |destinationRealm| in |destinationRealms|:

        1. Let |name| be the empty string. This will be used to report <a>minimal culprit attribution</a>, below.
        1. Let |culpritSettings| be <code>null</code>.
        1. If the |task| argument was not provided, set |name| to "<code><a>unknown</a></code>".
        1. Otherwise: process |task|'s <a>script evaluation environment settings object set</a> to determine |name| and |culpritSettings| as follows:

            1. If |task|'s <a>script evaluation environment settings object set</a> is empty: set |name| to "<code><a>unknown</a></code>" and |culpritSettings| to <code>null</code>.
            1. If |task|'s <a>script evaluation environment settings object set</a>'s length is greater than one: set |name| to "<code><a>multiple-contexts</a></code>" and |culpritSettings| to <code>null</code>.
            1. If |task|'s <a>script evaluation environment settings object set</a>'s length is one:
                1. Set |culpritSettings| to the single item in |task|'s <a>script evaluation environment settings object set</a>.
                1. Let |destinationSettings| be |destinationRealm|'s <a>relevant settings object</a>.
                1. Let |destinationOrigin| be |destinationSettings|'s [=environment settings object/origin=].
                1. Let |destinationBC| be |destinationSettings|'s <a>responsible browsing context</a>.
                1. If |culpritSettings| is the same as |destinationSettings|, set |name| to "<code><a>self</a></code>".
                1. If |culpritSettings|'s [=environment settings object/origin=] and |destinationOrigin| are <a>same origin</a>:
                    1. If |culpritSettings|'s <a>responsible browsing context</a> is an <a>ancestor</a> of |destinationBC|, set |name| to "<code><a>same-origin-ancestor</a></code>".
                    1. Otherwise, if |culpritSettings|'s <a>responsible browsing context</a> is a <a lt="list of the descendant browsing contexts">descendant</a> of |destinationBC|, set |name| to "<code><a>same-origin-descendant</a></code>".
                    1. Otherwise, set |name| to "<code><a>same-origin</a></code>".
                1. Otherwise:
                    1. If |culpritSettings|'s <a>responsible browsing context</a> is an <a>ancestor</a> of |destinationBC|, set |name| to "<code><a>cross-origin-ancestor</a></code>" and set |culpritSettings| to <code>null</code>.

                        NOTE: this is not reported because of security. Developers should look this up themselves.

                    1. Otherwise, if |culpritSettings|'s <a>responsible browsing context</a> is a <a lt="list of the descendant browsing contexts">descendant</a> of |destinationBC|, set |name| to "<code><a>cross-origin-descendant</a></code>".
                    1. Otherwise, set |name| to "<code><a>cross-origin-unreachable</a></code>".

        1. If |task| was not provided, let |attribution| be <code>null</code>.
        1. Otherwise, let |attribution| be a new {{TaskAttributionTiming}} object and set its attributes as follows:
            1. Set |attribution|'s {{PerformanceEntry/name}} attribute to "<code><a>unknown</a></code>".

                NOTE: future iterations of this API will add more values to the {{PerformanceEntry/name}} attribute of a {{TaskAttributionTiming}} object, but for now it can only be a single value.

            1. Set |attribution|'s {{PerformanceEntry/entryType}} attribute to <code>"taskattribution"</code>.
            1. Set |attribution|'s {{PerformanceEntry/startTime}} and {{PerformanceEntry/duration}} to 0.
            1. Set |attribution|'s {{containerType}} attribute to <code>"window"</code>.
            1. Set |attribution|'s {{containerName}} and {{containerSrc}} attributes to the empty string.
            1. If |culpritSettings| is not <code>null</code>:
                1. Let |container| be |culpritSettings|'s <a>responsible browsing context</a>'s <a>browsing context container</a>.
                1. Assert: |container| is not <code>null</code>.
                1. Set |attribution|'s {{containerId}} attribute to the value of |container|'s [=Element/ID=], or the empty string if the ID is unset.
                1. If |container| is an <{iframe}> element:
                    1. Set |attribution|'s {{containerType}} attribute to "<code>iframe</code>".
                    1. Set |attribution|'s {{containerName}} attribute to the value of |container|'s <{iframe/name}> content attribute, or the empty string if the attribute is absent.
                    1. Set |attribution|'s {{containerSrc}} attribute to the value of |container|'s <{iframe/src}> content attribute, or the empty string if the attribute is absent.

                    NOTE: it is intentional that we record the frame's <{iframe/src}> attribute here, and not its current URL, as this is meant primarily to help identify frames, and allowing discovery of the current URL of a cross-origin iframe is a security problem.

                1. If |container| is a <{frame}> element:
                    1. Set |attribution|'s {{containerType}} attribute to "<code>frame</code>".
                    1. Set |attribution|'s {{containerName}} attribute to the value of |container|'s <code>name</code> content attribute, or the empty string if the attribute is absent.
                    1. Set |attribution|'s {{containerSrc}} attribute to the value of |container|'s <code>src</code> content attribute, or the empty string if the attribute is absent.
                1. If |container| is an <{object}> element:
                    1. Set |attribution|'s {{containerType}} attribute to "<code>object</code>".
                    1. Set |attribution|'s {{containerName}} attribute to the value of  |container|'s <{object/name}> content attribute, or the empty string if the attribute is absent.
                    1. Set |attribution|'s {{containerSrc}} attribute to the value of |container|'s <{object/data}> content attribute, or the empty string if the attribute is absent.
                1. If |container| is an <{embed}> element:
                    1. Set |attribution|'s {{containerType}} attribute to "<code>embed</code>".
                    1. Set |attribution|'s {{containerName}} attribute to the empty string.
                    1. Set |attribution|'s {{containerSrc}} attribute to the value of |container|'s <{embed/src}> content attribute, or the empty string if the attribute is absent.

        1. Create a new {{PerformanceLongTaskTiming}} object |newEntry| and set its attributes as follows:

            1. Set |newEntry|'s {{PerformanceEntry/name}} attribute to |name|.
            1. Set |newEntry|'s {{PerformanceEntry/entryType}} attribute to "<code>longtask</code>".
            1. Set |newEntry|'s {{PerformanceEntry/startTime}} attribute to |start time|.
            1. Set |newEntry|'s {{PerformanceEntry/startTime}} attribute to |end time| minus |start time|.
            1. If |attribution| is not <code>null</code>, set |newEntry|'s {{PerformanceLongTaskTiming/attribution}} attribute to a new frozen array containing the single value |attribution|.

                NOTE: future iterations of this API will add more values to the {{PerformanceLongTaskTiming/attribution}} attribute, but for now it only contains a single value.

        1. <a>Queue the PerformanceEntry</a> |newEntry| on |destinationRealm|.
</div>

Security & privacy considerations {#priv-sec}
===============================================

Long Tasks API adheres to the same-origin policy by including origin-safe attribution information about the source of the long task.
There is a 50ms threshold for long tasks. Together this provides adequate protection against security attacks against browser.

However, privacy related attacks are possible, while the API doesn’t introduce any new privacy attacks, it could make existing privacy attacks faster. Mitigations for this are possible and discussed in the security review <a href="https://docs.google.com/document/d/1tIMI1gau_q6X5EBnjDNiFS5NWV9cpYJ5KKA7xPd3VB8/edit">in this document</a>.
